因為如果把dialog寫在viewmodel裡面,之後在自動化測試的時候可能會出問題,所以在mvvm架構底下,我們另外寫了一個dialogviewmodel,對應到dialog的view
首先先建立一個dialogviewmodel
class DialogViewModel: ViewModel() {
val result: MutableLiveData = MutableLiveData()
}
然後建立一個狀態資訊
//表達一個元件的狀態
//sealed可以使用dataclass傳值
sealed class MainDialogResult {
data class Ok(val message: String): MainDialogResult()
object Cancel: MainDialogResult()
//也可以使用object變成跟enum一樣的用法
}
然後在dialogfragment中這樣調用
class FragmentDialog: DialogFragment() {
private val viewModel: DialogViewModel<MainDialogResult> by activityViewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater.inflate(R.layout.dialogfragment , container , false)
val accountEditView = view.findViewById<EditText>(R.id.account)
val passwordEditView = view.findViewById<EditText>(R.id.password)
val loginButton = view.findViewById<Button>(R.id.login)
val cancelButton = view.findViewById<Button>(R.id.cancel)
val progressBar = view.findViewById<ProgressBar>(R.id.progressBar)
val pgBar = view.findViewById<ProgressBar>(R.id.progressBar2)
progressBar.visibility = View.VISIBLE
pgBar.max = 100
Thread{
for (i in 0..100){
pgBar.progress = i
//Thread.sleep(500)
SystemClock.sleep(500)
}
}.start()
pgBar.progress = 0
val message = "ok"
loginButton.setOnClickListener {
viewModel.result.postValue(MainDialogResult.Ok(message))
dismiss()
}
cancelButton.setOnClickListener {
viewModel.result.postValue(MainDialogResult.Cancel)
dismiss()
}
return view
}
}
最後在activity中這要調用即可
val fm = supportFragmentManager
val dialog = FragmentDialog()
dialog.show(fm,"Blossom")
viewModel.result.observe(this){
when(it){
is MainDialogResult.Ok ->{
Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
}
is MainDialogResult.Cancel ->{
Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
}
}